{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mask2rle(img):\n",
    "    '''\n",
    "    Convert mask to rle.\n",
    "    img: numpy array,\n",
    "    1 - mask,\n",
    "    0 - background\n",
    "\n",
    "    Returns run length as string formated\n",
    "    '''\n",
    "    pixels = img.T.flatten()  # 转置后看图像\n",
    "    pixels = np.concatenate([[0], pixels, [0]])\n",
    "    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n",
    "    runs[1::2] -= runs[::2]\n",
    "    return ' '.join(str(x) for x in runs)\n",
    "\n",
    "def files_mask2rle(path):\n",
    "    '''\n",
    "    批量将mask转为rlu\n",
    "    :param path:\n",
    "    :return:\n",
    "    '''\n",
    "    files = os.listdir(path)\n",
    "    csv = open(r'predict.csv', 'w')\n",
    "    for file in files:\n",
    "        fp = os.path.join(path, file)\n",
    "        img = cv2.imread(fp)\n",
    "        w, h = img.shape[1::-1]\n",
    "        img = img[:, :, 0]\n",
    "        img = img // 255\n",
    "        result = mask2rle(img)\n",
    "        csv.writelines(\"{},{} {},{}\\n\".format(file, w, h, result))\n",
    "\n",
    "def files_rle2mask(csv, save_path):\n",
    "    '''\n",
    "    批量将rle转为mask\n",
    "    :param csv:\n",
    "    :return:\n",
    "    '''\n",
    "\n",
    "    for line in open(csv, 'r').readlines():\n",
    "        arrs = line.split(',')\n",
    "        name = arrs[0]\n",
    "        w, h = list(map(int, arrs[1].split(' ')))\n",
    "        rle = arrs[2]\n",
    "        image = rle_decode(rle, (h, w))\n",
    "        image = image * 255\n",
    "        cv2.imwrite(os.path.join(save_path, name), image)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "if __name__ == '__main__':\n",
    "    files_mask2rle(\"D:\\\\A DeepLearn\\\\testjie\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
